package org.vacoor.nothing.security.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.vacoor.nothing.common.codec.Base62;
import org.vacoor.nothing.common.util.Oid;
import org.vacoor.nothing.common.util.StringUtils;

import java.util.Date;
import java.util.Map;

/**
 *
 */
@RequestMapping("/signup")
public class SignUpController {

    @RequestMapping("send-mail")
    public String sendActivateEmail(String email, Map<String, Object> model) {
        if (!StringUtils.hasText(email)) {
            model.put("error", "Invalid Request");
        } else {
            // do send email
        }

        return "reg/activate";
    }

    @RequestMapping(value = "activate", method = RequestMethod.GET)
    public void activate(String account, String safeKey) {
        try {
            Oid clientKey = StringUtils.hasText(safeKey) ? new Oid(Base62.decode(safeKey)) : null;
            Oid serverKey;
            /*
            User u = userService.findUser(account);
            safeKey = null != u ? u.getSafeKey() : null;
            */
            serverKey = StringUtils.hasText(safeKey) ? new Oid(Base62.decode(safeKey)) : null;

            int expired = 30 * 60;
            if (null == serverKey || !serverKey.equals(clientKey)) {
                // invalid safekey
                throw new InvalidSafeKeyException("safe key is invalid or expired");
            }

            if (new Date().getTime() / 1000 - serverKey.getTimestamp() > expired) {
                // expired
                throw new InvalidSafeKeyException("safe key is invalid or expired");
            }
        } catch (Throwable e) {
            throw e instanceof InvalidSafeKeyException ? (InvalidSafeKeyException) e : new InvalidSafeKeyException(e);
            // model.add("error", "验证码不合法或已经过期")
        }
    }

    @RequestMapping(value = "activate", method = RequestMethod.POST)
    public void activate(String account, String safeKey, String password, String confirmPassword) {
        // validate safeKey
        // delete db safe key
        // 修改成功, 验证码不合法或已经过期
    }
}
